package dao;

/**
 *
 * @author yakimovich
 */
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.DriverConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

/**
 *
 * @author Yana
 */
public abstract class AbstractJdbcDao {

    private static DataSource dataSource;
    protected Connection connection;
    protected String driverName = "org.h2.Driver";
    protected String uri = "jdbc:h2:jdbc_project";
    protected String username = "sa";
    protected String password = "";
    /**
     * Create logger.
     */
    protected static org.apache.commons.logging.Log logger =
            LogFactory.getLog(AbstractJdbcDao.class);

    /**
     * Create connection.
     *
     * @return Connection with DB
     */
    public Connection createConnection() {

        try {
            if (dataSource == null) {
                dataSource = getDataSource();
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            logger.error(this, e);
            throw new IllegalStateException(e);
        }
        return connection;
    }

    /**
     * Create DataSource with the specified parameters.
     *
     * @return object of class DataSource
     *
     */
    private DataSource getDataSource() {

        Properties prop = new Properties();
        prop.setProperty("user", username);
        prop.setProperty("password", password);

        Driver driver = null;
        try {
            driver = (Driver) Class.forName(driverName).newInstance();
        } catch (InstantiationException e) {
            logger.error(this, e);
            throw new IllegalStateException(e);
        } catch (IllegalAccessException e) {
            logger.error(this, e);
            throw new IllegalStateException(e);
        } catch (ClassNotFoundException e) {
            logger.error(this, e);
            throw new IllegalStateException(e);
        }

        PoolableConnectionFactory factory = new PoolableConnectionFactory(
                new DriverConnectionFactory(driver, uri, prop),
                new GenericObjectPool(null), null, "SELECT 1", false, true);
        DataSource src = new PoolingDataSource(factory.getPool());
        return src;
    }
}
